package com.mjsoftking.aopapp.aop.aspect;

import android.view.View;

import com.mjsoftking.aopapp.aop.anno.ClickHook;
import com.mjsoftking.aopapp.aop.anno.ClickHook2;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 *
 */
@Aspect
public class ClickHookAspect {

    /**
     * 拦截检查是否登录过
     */
    @Around(value = "BaseAspect.clickHookAnnotation(clickHook)")
    public Object around(ProceedingJoinPoint joinPoint, ClickHook clickHook) throws Throwable {
        try {
            Signature signature = joinPoint.getSignature();
            if (!(signature instanceof MethodSignature)) {
                return joinPoint.proceed();
            }

            MethodSignature methodSignature = (MethodSignature) signature;
            for (Method m : methodSignature.getDeclaringType().getMethods()) {
                if (!m.isAnnotationPresent(ClickHook2.class)) {
                    continue;
                }
                ClickHook2 hook2 = m.getAnnotation(ClickHook2.class);
                View view = getViewFromArgs(joinPoint.getArgs());

                if(null != view && view.getId() == hook2.value()){
                    m.invoke(joinPoint.getThis(), joinPoint.getArgs());
                    return joinPoint.proceed();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        return joinPoint.proceed();
    }

    /**
     * 只识别第一个参数是不是click事件的view
     * @param args
     * @return
     */
    private View getViewFromArgs(Object[] args) {
        if(null == args) return null;

        return args[0] instanceof View ? (View) (args[0]) : null;
    }
}
